//
//  NetworkTools.m
//  OC ~ AFN
//
//  Created by teacher on 16/4/17.
//  Copyright © 2016年 TiffanyBao. All rights reserved.
//

#import "NetworkTools.h"

@protocol NetworkToolsProxy <NSObject>

@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end



@interface NetworkTools()<NetworkToolsProxy>

@end


@implementation NetworkTools

static NetworkTools *instance;

+ (instancetype)sharedTools {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [self manager];
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
        //请求格式
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        //请求超时
        instance.requestSerializer.timeoutInterval = 10.0;
    });
    return instance;
}

// 以后碰到：如果已经知道某个类身上有这个方法，但是.h文件并没有申明，那么，我们可以曲线救国
// 自已定义一个协议，在协议里面将这个方法申明一下，自己再继承于这个协议。那么就可以调用

- (void)request:(RequestMethod)method urlString:(NSString *)urlString parameters:(id)parameters finished:(void (^)(id responseObject, NSError *error))finished{
    
    NSString *m = (method == RequestMethodGet) ? @"get" : @"post";
    [[self dataTaskWithHTTPMethod:m URLString:urlString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *dataTask, id responseObject) {
        
        // 请求成功的回调
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask *dataTasl, NSError *error) {
        // 请求失败
        finished(nil, error);
    }] resume];
}

@end
